const express = require("express")
const router = express.Router()
const homeHot = require("./data/home/homeHot")
const citys = require('./data/city/data.json')
const url = require("url");
const searchList = require("./data/search/data")
const shanghai = require("./data/home/shanghai_homeHot")
const details = require("./data/details/data")
const comment = require("./data/comment/data")
const clientFn = require("./mysql")
const jwt = require("jsonwebtoken")
const orderList = require("./data/order/data")


router.get("/hot1", (req, res) => {
  const city = url.parse(req.url, true).query.city;
  // console.log(city);
  if (city === "武汉") {
    res.send({
      status: 200,
      result: shanghai.hot1
    })
  } else {
    res.send({
      status: 200,
      result: homeHot.hot1
    })
  }
})

router.get("/hot2", (req, res) => {
  res.send({
    status: 200,
    result: homeHot.hot2
  })
})

// 城市列表
router.get("/city", (req, res) => {
  res.send({
    status: 200,
    result: citys
  })
})

// 搜索
router.get("/search", (req, res) => {
  const keywords = url.parse(req.url, true).query.keywords;
  // console.log(keywords);
  res.send({
    status: 200,
    result: searchList
  })
})

// 详情页
router.get("/details", (req, res) => {
  const id = url.parse(req.url, true).query.id;
  console.log(id);
  res.send({
    status: 200,
    result: details
  })
})


// 评论
router.get("/comment", (req, res) => {
  const id = url.parse(req.url, true).query.id;
  console.log(id);
  res.send({
    status: 200,
    result: comment
  })
})

// 登录
router.post("/login", (req, res) => {
  console.log(req.body);
  const {
    username,
    password
  } = req.body;
  const sql = "select * from user where username=? and password=?";
  const arr = [username, password];
  clientFn(sql, arr, result => {
    if (result.length > 0) {

      // 登录成功---创建token
      let token = jwt.sign({
        username: result[0].username,
        id: result[0].id
      }, 'helloToken') // 里面可以加过期时间，后台处理

      res.send({
        status: 200,
        msg: "登陆成功",
        token
      })
    } else {
      res.send({
        status: 400,
        msg: "登陆失败"
      })
    }
  })
})


// 订单列表
router.get("/order", (req, res) => {
  const user = url.parse(req.url, true).query.user;
  console.log(user);
  res.send({
    status: 200,
    result: orderList
  })
})



module.exports = router;